package src.linkeLlist;

public class no206 {
    //反转链表，三指针，用一个temp指针保存p->next
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);

        node1.next = node2;
        node2.next = node3;

        node3.next = null;
        reverseList(node1);
        System.out.println(node3.val);
        System.out.println(node3.next.val);
        System.out.println(node3.next.next.val);

    }

    public static ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode p = head;

        //p、pre同时后移，当p指null时，pre指最后一个node，即为新的头结点
        while (p != null) {
            ListNode temp = p.next;
            p.next = pre;
            pre = p;  //必须先移动pre，后移动p
            p = temp;
        }
        return pre;

    }
}
